﻿using Furion;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ADSTS_SERVER.Controllers
{
    /// <summary>
    /// 文件上传
    /// </summary>
    [DynamicApiController]
    public class LnsUploadController
    {
        private readonly ILogger<LnsUploadController> logger;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public LnsUploadController(ISqlSugarClient sqlSugarClient, ILogger<LnsUploadController> logger)
        {
            this.db = sqlSugarClient;
            this.logger = logger;
        }

        /// <summary>
        /// 多文件上传，目录参数（dir）支持多级
        /// </summary>
        /// <param name="files">文件列表</param>
        /// <param name="dir">目录参数支持多级</param>
        /// <returns></returns>
        [HttpPost]
        [DisableRequestSizeLimit, RequestFormLimits(MultipartBodyLengthLimit = long.MaxValue)]
        public async Task<IActionResult> Resources([FromForm] List<IFormFile> files, [FromForm] string dir)
        {
            string uploadPath = Path.Combine(App.WebHostEnvironment.WebRootPath, "upload", dir);
            List<string> data = new();
            long size = files.Sum(f => f.Length);
            foreach (var formFile in files)
            {
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + formFile.FileName;
                if (formFile.Length > 0)
                {
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }
                    var filePath = Path.Combine(uploadPath, fileName);

                    using (var stream = System.IO.File.Create(filePath))
                    {
                        await formFile.CopyToAsync(stream);
                    }

                    data.Add($"/upload/{dir}/" + fileName);
                }
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除多目录
        /// </summary>
        /// <param name="dirs"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DeleteDirs([FromBody] List<string> dirs)
        {
            dirs.ForEach(dir =>
            {
                Directory.Delete(Path.Combine(App.WebHostEnvironment.WebRootPath, dir), true);
            });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除多文件
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DeleteFiles([FromBody] List<string> files)
        {
            files.ForEach(file =>
            {
                File.Delete(Path.Combine(App.WebHostEnvironment.WebRootPath, file));
            });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
